// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const net = require('net')
var isConnected = false
var PORT = 1527;
var client = new net.Socket();
var appOut = vscode.window.createOutputChannel("Vassist Output")

const traversingViewScript = "requireAccessibility()\ntraversing(rootView())\n" + "print(runtime.currentApp)"

var lastIp = "192.168.137.182"
var lastCmd = null

client.on("data", function (data) {//app消息
    appOut.show(true)
    appOut.append(data.toString())
})
client.on("close", function () {
    if (isConnected) {
        appOut.show(true)
        appOut.appendLine("断开连接")
    }
    else {
        appOut.show(true)
        appOut.appendLine("连接失败")
    }
    isConnected = false
})
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {

    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('"vassist-debugger" is now active!');

    // The command has been defined in the package.json file
    // Now provide the implementation of the command with  registerCommand
    // The commandId parameter must match the command field in package.json
    //连接手机
    let commandConnect = vscode.commands.registerCommand('extension.connect', function () {
        // The code you place here will be executed every time your command is executed
        vscode.window.showInputBox({
            placeHolder: "输入手机ip（同一局域网）",
            value: lastIp
        }).then(function (s) {
            console.log(s)
            lastIp = s
            connect(s)
        })
    });
    //关闭连接
    let closeConnect = vscode.commands.registerCommand('extension.closeConnect', function () {
        if (isConnected)
            client.destroy()
        else
            showInfo("未连接")
    });
    //测试运行
    let testRun = vscode.commands.registerCommand('extension.testRun', function () {
        if (!isConnected) {
            showInfo("请先连接手机")
            return
        }
        var s = getSeletedText()
        if (s == null) showInfo("未选择文件")
        else
            send(wrapAction("run", getType(), s))
    });
    let stopRun = vscode.commands.registerCommand('extension.stopRun', function () {
        if (!isConnected) {
            showInfo("请先连接手机")
            return
        }
        send(wrapAction("stop", null, null))
    });
    let traversingView = vscode.commands.registerCommand('extension.traversingView', function () {
        if (!isConnected) {
            showInfo("请先连接手机")
            return
        }
        send(wrapAction("run", 'lua', traversingViewScript))
    });
    let uploadInstAsGlobal = vscode.commands.registerCommand('extension.uploadInstAsGlobal', function () {
        if (!isConnected) {
            showInfo("请先连接手机")
            return
        }
        var s = getSeletedText()
        if (s == null) showInfo("未选择文件")
        else
            send(wrapAction("new_inst_as_global", getType(), s))
    });
    let uploadInstAsInApp = vscode.commands.registerCommand('extension.uploadInstAsInApp', function () {
        if (!isConnected) {
            showInfo("请先连接手机")
            return
        }
        var s = getSeletedText()
        if (s == null) showInfo("未选择文件")
        else
            send(wrapAction("new_inst_as_inapp", getType(), s))
    });
    let copyToClip = vscode.commands.registerCommand('extension.copyToClip', function () {
        if (!isConnected) {
            showInfo("请先连接手机")
            return
        }
        var s = getSeletedText()
        if (s == null) showInfo("未选择文件")
        else
            send(wrapAction("copyText", null, s))
    });
    let runCommand = vscode.commands.registerCommand('extension.runCommand', function () {
        if (!isConnected) {
            showInfo("请先连接手机")
            return
        }
        vscode.window.showInputBox({
            placeHolder: "执行命令",
            value: lastCmd
        }).then(function (s) {
            console.log(s)
            lastCmd = s
            send(wrapAction("command", null, s))
        })
    });

    createStatusBarIcons()

    context.subscriptions.push(commandConnect);
    context.subscriptions.push(closeConnect);
    context.subscriptions.push(testRun);
    context.subscriptions.push(stopRun);
    context.subscriptions.push(traversingView);
    context.subscriptions.push(runCommand);
    context.subscriptions.push(uploadInstAsGlobal);
    context.subscriptions.push(uploadInstAsInApp);
    context.subscriptions.push(copyToClip);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {
    if (isConnected)
        client.destroy()
    console.log("deactivate")
}
exports.deactivate = deactivate;
//连接
function connect(ip) {
    if (!ip) {
        // vscode.window.showInformationMessage("")
        return
    }
    client.destroy()
    client.connect(PORT, ip, function () {
        isConnected = true
        vscode.window.showInformationMessage("建立连接：" + client.remoteAddress)
    })
    console.log("连接手机：" + ip)
}
//文件类型
function getType() {
    var lang = vscode.window.activeTextEditor.document.languageId
    console.log(lang)
    if (lang === "lua" || lang === "javascript") {
        return lang
    }
    return null
}

//封装
/**
 * 
 * @param {*} action 空-> 获取编辑器内容 非空指定文本
 * @param {*} script 
 */
function wrapAction(action, type, script) {
    if (action === "run" && type == null) {
        showInfo("不支持的文件类型")
        return null
    }

    return JSON.stringify({
        action: action,//动作
        type: type,//脚本类型
        text: script//内容
    })
}
//发送socket
function send(json) {
    if (json == null) {
        return
    }
    console.log(json)
    client.write(json + "\n", "utf8")
}

function showInfo(s) {
    console.log(s)
    vscode.window.showInformationMessage(s)
}
//获取编辑框选择文本
function getSeletedText() {
    try {
        var doc = vscode.window.activeTextEditor.document
        var sel = vscode.window.activeTextEditor.selection
        var script = ""
        if (sel.isEmpty) {//未选择
            script = doc.getText()
        } else { //build script
            var statLine = sel.start.line
            var endLine = sel.end.line

            script += doc.lineAt(statLine).text.substring(sel.start.character) + "\n"
            for (var l = statLine + 1; l < endLine; l++) {
                script += doc.lineAt(l).text + "\n"
            }
            if (statLine != endLine)
                script += doc.lineAt(endLine).text.substring(0, sel.end.character)
        }
        console.log(script);
        return script
    } catch (e) {
        return null
    }
}

function createStatusBarIcons() {
    //状态栏-连接
    showButton(50, 'extension.connect', `$(zap)`, "连接手机", "yellow")

    //状态栏-断开连接
    showButton(45, 'extension.closeConnect', `$(x)`, "断开连接", "red")
    //状态栏-运行
    showButton(44, 'extension.testRun', `$(triangle-right)`, "运行", "yellow")

    //状态栏-停止
    showButton(40, 'extension.stopRun', `$(primitive-square)`, "停止", "red")

    //状态栏-命令
    showButton(30, 'extension.runCommand', `$(terminal)`, "运行指令", null)
    //状态栏-打印屏幕
    showButton(20, 'extension.traversingView', `$(device-camera)`, "输出布局", null)
    //上传代码到新建指令页面
    showButton(10, 'extension.uploadInstAsGlobal', `$(arrow-up)`, "新建全局指令", "light-green")
    showButton(5, 'extension.uploadInstAsInApp', `$(arrow-up)`, "新建App内指令", "yellow")
    showButton(4, 'extension.copyToClip', `$(clippy)`, "复制到手机剪切板", null)

}

function showButton(p, commmand, text, tooltip, color) {

    let button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, p);
    button.command = commmand;
    button.text = text;
    button.tooltip = tooltip;
    if (color)
        button.color = color
    button.show();
}